package cn.icanci.ladybird.service.admin.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.icanci.ladybird.common.result.JsonData;
import cn.icanci.ladybird.common.util.FileUtils;
import cn.icanci.ladybird.common.util.FtpUtil;
import cn.icanci.ladybird.common.util.RandomValueUtils;
import cn.icanci.ladybird.pojo.bo.AdminUploadTicketBO;
import cn.icanci.ladybird.pojo.entity.*;
import cn.icanci.ladybird.service.*;
import cn.icanci.ladybird.service.admin.AdminUploadTicketService;
import cn.icanci.ladybird.service.util.NginxService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

/**
 * @author: icanci
 * @date: Created in 2020/10/5 1:23
 * @classAction: 处理票上传信息
 */
@SuppressWarnings("all")
@Service
@Slf4j
public class AdminUploadTicketServiceImpl implements AdminUploadTicketService {
    @Autowired
    private TicketDetailsService ticketDetailsService;
    @Autowired
    private NginxService nginxService;
    @Autowired
    private TicketDetailsTicketTimeMiddleService ticketDetailsTicketTimeMiddleService;
    @Autowired
    private TicketTimeService ticketTimeService;
    @Autowired
    private TicketSeatService ticketSeatService;
    @Autowired
    private TicketPriceService ticketPriceService;
    @Autowired
    private TicketDetailsTicketPriceMiddleService ticketDetailsTicketPriceMiddleService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public JsonData uploadHandler(HttpServletRequest request, AdminUploadTicketBO adminUploadTicketBO) {
        try {
            // 处理数据
            // 创建票对象
            TicketDetails ticketDetails = new TicketDetails();
            // 设置商品名字
            ticketDetails.setTicketDetailsInfo(adminUploadTicketBO.getTicketName());
            // 设置创建时间和更新时间
            ticketDetails.setCreateTime(new Date());
            ticketDetails.setUpdateTime(new Date());
            // 设置状态
            ticketDetails.setTicketDetailsStatus(Integer.valueOf(adminUploadTicketBO.getTicketStatus()));
            // 设置是否是秒室
            ticketDetails.setTicketDetailsIsKill(Integer.valueOf(adminUploadTicketBO.getIsKilled()));
            // 设置演出城市
            ticketDetails.setTicketAddressCity(adminUploadTicketBO.getCity());
            // 设置演出场馆
            ticketDetails.setTicketAddressVenue(adminUploadTicketBO.getVenue());
            // 设置权重值
            ticketDetails.setTicketDetailsWeight(Integer.valueOf(adminUploadTicketBO.getTicketWeight()));

            // 图片文件上传
            List<MultipartFile> files = adminUploadTicketBO.getFiles();
            long begin = System.currentTimeMillis();
            Map<Object, Object> map = new HashMap<>(4);
            int count = 0;
            for (MultipartFile file : files) {
                Object result = nginxService.uploadPicture(file);
                log.info("AdminUploadTicketServiceImpl.uploadHandler - result " + result);
                if (count == 2) {
                    String[] split = result.toString().split("/");
                    // 得到的是文件上传之后的相对路径
                    String rootPath = FtpUtil.ROOT_PATH + split[split.length - 2] + "/" + split[split.length - 1];
                    log.info("AdminUploadTicketServiceImpl.uploadHandler - rootPath " + rootPath);
                    // 云服务器根目录
                    map.put(count, rootPath);
                    // 文件的url地址
                    map.put(count + 1, result);
                }else {
                    map.put(count, result);
                }
                count++;
            }

            // 设置图片
            ticketDetails.setTicketDetailsTicketImgUrl(map.get(0).toString());
            ticketDetails.setTicketDetailsTicketImgInfoUrl(map.get(1).toString());
            // 设置文件地址
            ticketDetails.setTicketDetailsExcelAddress(map.get(3).toString());
            Integer adminId = (Integer) request.getAttribute("admin_id");
            ticketDetails.setTicketDetailsAdminId(Long.valueOf(adminId));

            // 保存 service
            ticketDetailsService.insert(ticketDetails);

            // 获取票的 id
            Long ticketDetailsId = ticketDetails.getTicketDetailsId();
            // 创建票和价格中间表 设置时间
            ArrayList<Date> dates = new ArrayList<>();
            Date parse1 = DateUtil.parse(adminUploadTicketBO.getTime1());
            Date parse2 = DateUtil.parse(adminUploadTicketBO.getTime2());
            Date parse3 = DateUtil.parse(adminUploadTicketBO.getTime3());
            dates.add(parse1);
            dates.add(parse2);
            dates.add(parse3);
            for (Date date : dates) {
                TicketTime ticketTime = new TicketTime();
                ticketTime.setTicketTime(date);
                ticketTime.setCreateTime(new Date());
                ticketTime.setUpdateTime(new Date());
                ticketTimeService.insert(ticketTime);
                TicketDetailsTicketTimeMiddle timeMiddle = new TicketDetailsTicketTimeMiddle();
                timeMiddle.setTicketDetailsMiddleId(ticketDetailsId);
                timeMiddle.setTicketTimeMiddleId(ticketTime.getTicketTimeId());
                timeMiddle.setCreateTime(new Date());
                timeMiddle.setUpdateTime(new Date());
                ticketDetailsTicketTimeMiddleService.insert(timeMiddle);
            }
            // 获取文件读取数据流
            log.info("AdminUploadTicketServiceImpl.uploadHandler -  map.get(0) - " + map.get(1).toString());
            log.info("AdminUploadTicketServiceImpl.uploadHandler -  map.get(1) - " + map.get(0).toString());
            log.info("AdminUploadTicketServiceImpl.uploadHandler -  map.get(2) - " + map.get(2).toString());
            log.info("AdminUploadTicketServiceImpl.uploadHandler -  map.get(3) - " + map.get(3).toString());
            ExcelReader reader = ExcelUtil.getReader(map.get(2).toString());
            List<List<Object>> read = reader.read();
            // 对读取的数据进行处理 包含横坐标，纵坐标，座位价格，是否可用，座位状态
            ArrayList<TicketSeat> ticketSeats = new ArrayList<>();
            HashSet<Double> priceSet = new HashSet<>();
            for (int i = 1; i < read.size(); i++) {
                List<Object> temp = read.get(i);
                // 类型转换
                Integer ticketX = Integer.valueOf(temp.get(0).toString());
                Integer ticketY = Integer.valueOf(temp.get(1).toString());
                Double ticketPrice = Double.valueOf(temp.get(2).toString());
                Integer ticketEnable = Integer.valueOf(temp.get(3).toString());
                Integer ticketState = Integer.valueOf(temp.get(4).toString());
                // 保存价格
                priceSet.add(ticketPrice);
                // 封装对象
                TicketSeat ticketSeat = new TicketSeat();
                ticketSeat.setTicketX(ticketX);
                ticketSeat.setTicketY(ticketY);
                ticketSeat.setTicketPrice(ticketPrice);
                ticketSeat.setTicketEnable(ticketEnable);
                ticketSeat.setTicketState(ticketState);
                ticketSeat.setTicketDetailsId(ticketDetailsId);
                ticketSeat.setCreateTime(new Date());
                ticketSeat.setUpdateTime(new Date());
                // 保存座位的信息
                ticketSeatService.insert(ticketSeat);
            }
            // 关闭资源
            // reader.close();
            // 插入价格

            Iterator<Double> iterator = priceSet.iterator();
            while (iterator.hasNext()) {
                Double next = iterator.next();
                TicketPrice ticketPrice = new TicketPrice();
                ticketPrice.setTicketPricePrice(next);
                ticketPrice.setCreateTime(new Date());
                ticketPrice.setUpdateTime(new Date());
                System.err.println(ticketPrice);
                ticketPriceService.insert(ticketPrice);
                // 插入价格和票的中间表
                TicketDetailsTicketPriceMiddle priceMiddle = new TicketDetailsTicketPriceMiddle();
                priceMiddle.setTicketPriceMiddleId(ticketPrice.getTicketPriceId());
                priceMiddle.setTicketDetailsMiddleId(ticketDetailsId);
                priceMiddle.setCreateTime(new Date());
                priceMiddle.setUpdateTime(new Date());
                ticketDetailsTicketPriceMiddleService.insert(priceMiddle);
            }
            long end = System.currentTimeMillis();
            log.info("任务结束，共耗时：[" + (end - begin) + "]毫秒");
        } catch (Exception e) {
            System.out.println(e);
            return JsonData.builderError(e.getLocalizedMessage());
        }
        return JsonData.builderSuccess("插入 success");
    }
}
